package com.uwlaser.webservice.client;

import com.predic8.schema.Element;
import com.predic8.wsdl.AbstractSOAPBody;
import com.predic8.wsdl.AbstractSOAPHeader;
import com.predic8.wsdl.BindingElement;
import com.predic8.wsdl.Part;
import com.uwlaser.utils.StringUtils;
import lombok.Data;
import com.predic8.wsdl.soap11.SOAPBody;
import com.predic8.wsdl.soap11.SOAPHeader;
import java.util.List;


/**
 * @Author QZK
 * @Description 方法实体
 * @Date 2022-11-23-15:04
 * @Version 1.0
 */
@Data
public class WsdlMethodEntity {

    public static final String SOAP11_SIGN = "xmlns:s11";

    public static final String SOAP12_SIGN = "xmlns:s12";

    /**
     * 方法名称
     */
    private String methodName;
    /**
     * 协议版本
     */
    private String version;

    /**
     * 请求模板
     */
    private String requestTemplate;

    /**
     * 请求头
     */
    private String soapHeader;

    /**
     * 请求体
     */
    private String soapBody;

    /**
     * 绑定参数
     */
    private List<BindingElement> bindingElements;

    public void setSoapHeader(String soapHeader) {
        this.soapHeader = soapHeader;
    }

    public void setSoapBody(String soapBody) {
        this.soapBody = soapBody;
    }

    /**
     * 获取方法请求头JSON格式
     * @return
     */
    public String getSoapHeader(){
        if(!StringUtils.isEmpty(this.soapHeader)){
            return this.soapHeader;
        }
        //解析Element标签，代表参数名
        for (BindingElement it : bindingElements) {
            //解析请求头标签
            if(it instanceof SOAPHeader || it instanceof com.predic8.wsdl.soap12.SOAPHeader){
                try {
                    Part part = ((AbstractSOAPHeader) it).getPart();
                    Element element = part.getElement();
                    this.soapHeader = element.getAsJson();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return this.soapHeader;
    }

    /**
     * 获取方法请求头JSON格式
     * @return
     */
    public String getSoapBody(){
        if(!StringUtils.isEmpty(this.soapBody)){
            return this.soapBody;
        }
        //解析Element标签，代表参数名
        for (BindingElement it : bindingElements) {
            //解析请求体标签
            if(it instanceof SOAPBody || it instanceof com.predic8.wsdl.soap12.SOAPBody){
                List<Part> parts = ((AbstractSOAPBody) it).getParts();
                for (Part part : parts) {
                    Element element = part.getElement();
                    this.soapBody = element.getAsJson();
                }
            }
        }
        return this.soapBody;
    }

    public void setRequestTemplate(String requestTemplate){
        if(requestTemplate.indexOf(SOAP11_SIGN) != -1){
            this.version = SOAP11_SIGN;
        } else {
            this.version = SOAP12_SIGN;
        }
        this.requestTemplate = requestTemplate;
    }
}
